<?php

namespace App\Manage;


use App\Service\Base\Manage;
use Illuminate\Support\Facades\Cookie;
use App\Models\Admin;

class AccountManage extends Manage
{
    // 个人账户

    // 初始化
    public function initialize()
    {
        parent::initialize();
    }


    // 修改
    public function onEdit()
    {
        $opt = $this->option();
        if(empty($opt->getUser())){
            return $this->_returnFail('请登录后在操作！！', LOGIN_ERROR);
        }

        $data = [
            //'username' => $opt->getData('username', null, 'trim'),
            //'role'     => $opt->getData('role', null, 'trim'),
            'nickname' => $opt->getData('nickname', null, 'trim'),
            'password' => $opt->getData('password', null, 'trim'),
            'mobile'   => $opt->getData('mobile', null, 'trim'),
            //'status'   => $opt->getData('status', 1, 'intval),
        ];

        // 检查唯一性
        $model = new Admin();
        $data  = $this->filterNull($data);
        $data  = $model->checkData($data);
        if($data === false){
            return $this->_returnFail($model->getError());
        }

        // 验证
        $result = $model->checkRules($data, 'info');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        $where  = ['id' => $opt->getUser('id')];
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 修改密码
    public function onPassword()
    {
        $opt = $this->option();
        if(empty($opt->getUser())){
            return $this->_returnFail('请登录后在操作！！', LOGIN_ERROR);
        }


        $data = ['password' => $opt->getData('password', null, 'trim'),];
        // 检查唯一性
        $model = new Admin();
        $data  = $this->filterNull($data);
        $data  = $model->checkData($data);
        if($data === false){
            return $this->_returnFail($model->getError());
        }

        $where  = ['id' => $opt->getUser('id')];
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $this->success();
    }

    // 登录
    public function onLogin()
    {
        // 参数
        $opt      = $this->option();
        $username = $opt->getData('username', null, 'trim');
        $password = $opt->getData('password', null, 'trim');

        // TODO 验证验证码


        // 登录操作
        $admin = new Admin();
        $user  = $admin->login($username, $password);  // 验证密码
        if($user === false){
            return $this->_returnFail($admin->getError());
        }

        // 权限整理
        //$user['roles'] = $admin->makeRoles($user['role'], true); // , $user['id'] == 1 ? true : false
        $user['uid'] = $user['id'];

        return $user;
    }


}


